
let currentUser = null;

// JWT认证检查
document.addEventListener('DOMContentLoaded', function() {
    const checkAuth = () => {
        if (window.AuthManager) {
            if (!window.AuthManager.isAuthenticated()) {
                showAccessDenied();
                return;
            }
            // 显示主要内容
            showMainContent();
            // 加载用户资料
            loadUserProfile();
            // 设置密码表单
            setupPasswordForm();
        } else {
            setTimeout(checkAuth, 100);
        }
    };
    checkAuth();
});

// 显示访问被拒绝
function showAccessDenied() {
    document.getElementById('accessDenied').style.display = 'block';
    document.getElementById('mainContent').style.display = 'none';
}

// 显示主要内容
function showMainContent() {
    document.getElementById('accessDenied').style.display = 'none';
    document.getElementById('mainContent').style.display = 'block';
}

// 显示成功提示
function showSuccess(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-success alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-check-circle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 3000);
}

// 显示错误提示
function showError(message) {
    const alertDiv = document.createElement('div');
    alertDiv.className = 'alert alert-danger alert-dismissible fade show position-fixed';
    alertDiv.style.cssText = 'top: 20px; right: 20px; z-index: 9999; min-width: 300px;';
    alertDiv.innerHTML = `
        <i class="bi bi-exclamation-triangle me-2"></i>
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        if (alertDiv.parentNode) {
            alertDiv.parentNode.removeChild(alertDiv);
        }
    }, 5000);
}

// 加载用户资料
async function loadUserProfile() {
    try {
        const response = await fetch('/ercms/api/users/current', {
            headers: window.AuthManager.getAuthHeaders()
        });
        const result = await response.json();
        if (result && result.id) {
            currentUser = result;
            displayUserProfile(result);
        } else {
            showError('加载用户资料失败');
        }
    } catch (error) {
        console.error('加载用户资料失败:', error);
        showError('加载用户资料失败，请检查网络连接');
    }
}

// 显示用户资料
function displayUserProfile(user) {
    // 基本信息
    document.getElementById('userId').textContent = user.id;
    document.getElementById('username').textContent = user.username;
    document.getElementById('realName').textContent = user.realName;
    document.getElementById('email').textContent = user.email || '-';
    document.getElementById('phone').textContent = user.phone || '-';
    document.getElementById('department').textContent = user.departmentName || '-';
    document.getElementById('createdAt').textContent = new Date(user.createdAt).toLocaleString();
    document.getElementById('updatedAt').textContent = new Date(user.updatedAt).toLocaleString();

    // 角色和状态
    const roleElement = document.getElementById('role');
    roleElement.textContent = getRoleDisplayName(user.role);
    roleElement.className = `badge bg-${getRoleBadgeColor(user.role)} role-badge`;

    const statusElement = document.getElementById('status');
    statusElement.textContent = user.enabled ? '启用' : '禁用';
    statusElement.className = `badge bg-${user.enabled ? 'success' : 'danger'} status-badge`;

    // 侧边栏显示
    document.getElementById('displayName').textContent = user.realName;
    document.getElementById('displayRole').textContent = getRoleDisplayName(user.role);

    // 最后登录时间（模拟）
    document.getElementById('lastLogin').textContent = new Date().toLocaleString();
}

// 显示编辑资料模态框
function showEditProfileModal() {
    if (!currentUser) return;

    document.getElementById('editRealName').value = currentUser.realName;
    document.getElementById('editEmail').value = currentUser.email || '';
    document.getElementById('editPhone').value = currentUser.phone || '';

    const modal = new bootstrap.Modal(document.getElementById('editProfileModal'));
    modal.show();
}

// 保存个人资料
async function saveProfile() {
    const formData = {
        realName: document.getElementById('editRealName').value,
        email: document.getElementById('editEmail').value,
        phone: document.getElementById('editPhone').value
    };

    if (!formData.realName.trim()) {
        showError('请输入真实姓名');
        return;
    }

    try {
        const response = await fetch(`/ercms/api/users/${currentUser.id}`, {
            method: 'PUT',
            headers: window.AuthManager.getAuthHeaders(),
            body: JSON.stringify(formData)
        });

        const result = await response.json();
        if (result.success) {
            showSuccess(result.message);
            bootstrap.Modal.getInstance(document.getElementById('editProfileModal')).hide();
            loadUserProfile(); // 重新加载资料
        } else {
            showError('更新失败: ' + result.message);
        }
    } catch (error) {
        console.error('更新失败:', error);
        showError('更新个人资料失败，请检查网络连接');
    }
}

// 设置密码表单
function setupPasswordForm() {
    document.getElementById('passwordForm').addEventListener('submit', async function(e) {
        e.preventDefault();
        await changePassword();
    });
}

// 修改密码
async function changePassword() {
    const currentPassword = document.getElementById('currentPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmNewPassword = document.getElementById('confirmNewPassword').value;

    if (!currentPassword || !newPassword || !confirmNewPassword) {
        showError('请填写所有密码字段');
        return;
    }

    if (newPassword !== confirmNewPassword) {
        showError('两次输入的新密码不一致');
        return;
    }

    if (newPassword.length < 6) {
        showError('新密码长度至少6位');
        return;
    }

    try {
        const response = await fetch('/ercms/api/users/change-password', {
            method: 'POST',
            headers: window.AuthManager.getAuthHeaders(),
            body: JSON.stringify({
                currentPassword: currentPassword,
                newPassword: newPassword
            })
        });

        const result = await response.json();
        if (result.success) {
            showSuccess(result.message);
            document.getElementById('passwordForm').reset();
            if (confirm('密码修改成功！建议重新登录以确保安全。是否现在退出登录？')) {
                window.AuthManager.logout();
                window.location.href = '/ercms/login';
            }
        } else {
            showError('密码修改失败: ' + result.message);
        }
    } catch (error) {
        console.error('修改密码失败:', error);
        showError('修改密码失败，请检查网络连接');
    }
}

// 聚焦密码表单
function focusPasswordForm() {
    document.getElementById('currentPassword').focus();
    document.getElementById('currentPassword').scrollIntoView({ behavior: 'smooth' });
}

// 刷新个人资料
function refreshProfile() {
    loadUserProfile();
}

// 辅助函数
function getRoleDisplayName(role) {
    const roleNames = {
        'ADMIN': '系统管理员',
        'DEPT_MANAGER': '部门管理员',
        'DISPATCHER': '调度员',
        'END_USER': '终端用户'
    };
    return roleNames[role] || role;
}

function getRoleBadgeColor(role) {
    const colors = {
        'ADMIN': 'danger',
        'DEPT_MANAGER': 'warning',
        'DISPATCHER': 'info',
        'END_USER': 'secondary'
    };
    return colors[role] || 'secondary';
}
